<template>
  <div>
    <head-tool>
      <template #right>
        <el-button size="small" type="danger" @click="doExport">导出</el-button>
        <el-button size="small" type="success" @click="$router.push('/import?ref=employees')">导入</el-button>
        <el-button
          size="small"
          type="primary"
          icon="el-icon-plus"
          @click="$refs.emp.dialogFormVisible = true"
        >新增员工</el-button>
      </template>
    </head-tool>
    <!-- 表格 -->
    <el-card class="table-card">
      <el-table :data="tableData" border style="width: 100%">
        <el-table-column type="index" label="序号" width="80" />
        <el-table-column prop="username" label="姓名" />
        <el-table-column prop="staffPhoto" label="头像" width="120">
          <template v-slot="{ row }">
            <img v-imgerr="defaultImg" style="width:60px;height:60px;border-radius:50%;" :src="row.staffPhoto" alt="" @click="clickImg(row.staffPhoto)">
          </template>
        </el-table-column>
        <el-table-column prop="mobile" label="手机号" width="150" />
        <el-table-column prop="workNumber" label="工号" />
        <el-table-column prop="formOfEmployment" label="聘用形式">
          <template v-slot="{row}">
            {{ row.formOfEmployment | formatHireType }}
          </template>
        </el-table-column>
        <el-table-column prop="departmentName" label="部门" />
        <el-table-column prop="timeOfEntry" label="入职时间" width="200" />
        <el-table-column prop="enableState" label="状态" />
        <el-table-column fixed="right" label="操作" width="250">
          <template v-slot="{row}">
            <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
            <el-button type="text" size="small">转正</el-button>
            <el-button type="text" size="small">调岗</el-button>
            <el-button v-if="checkPoint('EMP_OUT')" type="text" size="small">离职</el-button>
            <el-button type="text" size="small" @click="role(row.id)">角色</el-button>
            <el-button v-if="checkPoint('EMP_DEL')" type="text" size="small" @click="del(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div style="text-align:center;margin-top:10px;">
        <el-pagination
          :current-page="pageInfo.page"
          :page-size="pageInfo.size"
          :page-sizes="[5, 10, 20]"
          layout="sizes, total, prev, pager, next"
          :total="pageInfo.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
      <emp-dialog ref="emp" @add="add" />
    </el-card>

    <el-dialog title="图片二维码" :visible.sync="qrShow">
      <canvas ref="ca" />
    </el-dialog>

    <assign-role ref="role" />
  </div>
</template>

<script>
import { empListAPI, delEmpAPI } from '@/api/employees'
import enumObj from '@/utils/constant/employees'
import EmpDialog from './components/EmpDialog.vue'
import AssignRole from './components/AssignRole.vue'
import QRCode from 'qrcode'
export default {
  name: 'Employees',
  components: {
    EmpDialog,
    AssignRole
  },
  // 过滤器
  filters: {
    formatHireType(val) {
      const obj = enumObj.hireType.find(v => v.id === +val)
      return obj.value
    }
  },
  data() {
    return {
      qrShow: false,
      tableData: [],
      defaultImg: require('@/assets/common/head.jpg'),
      pageInfo: {
        page: 1,
        size: 10,
        total: 0
      }
    }
  },
  created() {
    this.getData()
  },
  methods: {
    add() {
      this.pageInfo.total++
      this.pageInfo.page = Math.ceil(this.pageInfo.total / this.pageInfo.size)
      this.getData()
    },
    async getData() {
      const res = await empListAPI(this.pageInfo)
      // 保存数据源
      this.tableData = res.data.rows
      // 保存总数量
      this.pageInfo.total = res.data.total
    },

    handleSizeChange(size) {
      this.pageInfo.size = size
      this.getData()
    },
    handleCurrentChange(page) {
      this.pageInfo.page = page
      this.getData()
    },

    // 删除的点击事件
    async del(id) {
      try {
        // 弹出一个确认框
        await this.$confirm('此操作将删除该员工, 是否继续?', '提示', {
          type: 'warning'
        })

        await delEmpAPI(id)
        // 弹出删除成功
        this.$message.success('删除成功！')
        // 重新加载数据
        this.getData()
      } catch {
        console.log('点了取消')
      }
    },
    // 导出的方法
    doExport() {
      // 懒加载element-admin帮我们封装好的导出excel的js文件
      // 参数excel就是这个文件里暴露的对象
      import('@/vendor/Export2Excel').then(async excel => {
        // 发请求获取所有员工的数据
        const res = await empListAPI({
          page: 1,
          size: this.pageInfo.total
        })

        // 中英文对照字典
        const userRelations = {
          入职日期: 'timeOfEntry',
          手机号: 'mobile',
          姓名: 'username',
          转正日期: 'correctionTime',
          工号: 'workNumber',
          聘用形式: 'formOfEmployment'
        }

        // 获取中文表头
        const header = Object.keys(userRelations)

        // 对返回的数据做map，产生一个新数组，新数组长度跟以前一样
        const data = res.data.rows.map(v => {
          const list = []

          // 遍历表头
          header.forEach(h => {
            // 此时h是中文还得转成英文
            const enKey = userRelations[h]
            list.push(v[enKey])
          })
          // 上面循环完了后，list里就有当前行的数据了
          return list
        })

        // 调用这个对象的这个方法就能做导出
        excel.export_json_to_excel({
          header, // 表头 必填
          data, // 具体数据 必填
          filename: '员工列表', // 导出的文件名
          autoWidth: true, // 自动宽度（让列的宽度跟内容一样宽）
          bookType: 'xlsx' // 非必填（导出的文件格式）
        })
      })
    },
    // 点击图片
    async clickImg(url) {
      // 绘制二维码
      this.qrShow = true
      await this.$nextTick()
      QRCode.toCanvas(this.$refs.ca, url)
    },
    // 点击角色
    role(id) {
      this.$refs.role.show(id)
    }
  }
}
</script>

<style lang="scss" scoped>
.table-card {
  margin-top: 20px;
}
</style>
